<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />

    

    

    <title>jest-vue测试套件使用 | 郑礼德技术栈</title>
    <meta name="author" content="郑礼德" />
    <meta name="keywords" content="" />
    <meta name="description" content="本文主要讲基于vue脚手架3.x 如何搭建单元测试框架，以及简单的测试新建vue项目安装vue脚手架3.x 版本使用npm list -g --depth 0 查看脚手架装的是vue-cli 还是@vue/cli  如果是vue-cli 使用npm uninstall vue-cli -g 卸载,然后使用npm install -g @vue/cli 重新安装新版本脚手架创建项目vue create vue-jest 创建项目选择自定义配置Manually select feat..." />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />

    
    <link rel="alternate" href="/homepage/atom.xml" title="郑礼德技术栈" type="application/atom+xml">
    
    
    <link rel="icon" href="/homepage/images/favicon.ico">
    

    <style type="text/css">
    @font-face {
        font-family: 'icomoon';
        src: url("/homepage/fonts/icomoon.eot?q628ml");
        src: url("/homepage/fonts/icomoon.eot?q628ml#iefix") format('embedded-opentype'),
             url("/homepage/fonts/icomoon.ttf?q628ml") format('truetype'),
             url("/homepage/fonts/icomoon.woff?q628ml") format('woff'),
             url("/homepage/fonts/icomoon.svg?q628ml#icomoon") format('svg');
        font-weight: normal;
        font-style: normal;
    }
    </style>
    
<link rel="stylesheet" href="/homepage/css/style.css">


    <!--[if lt IE 9]>
    <style type="text/css">
    .nav-inner {top:0;}
    .author-meta {position:static;top:0;}
    .search-form {height:36px;}
    </style>
    <script type="text/javascript" src="https://unpkg.com/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
    <![endif]-->
<meta name="generator" content="Hexo 4.2.0"></head>
<body>

    <main class="app">
        <header id="header" class="header clearfix">
    <div id="nav" class="nav">
    <div class="nav-mobile">
        <button id="open-panel" class="open-panel nav-mobile-item"><i class="icon-documents"></i></button>
        <h1 class="nav-mobile-title nav-mobile-item">郑礼德技术栈</h1>
        <button id="open-menus" class="open-panel nav-mobile-item"><i class="icon-library"></i></button>
    </div>

    <nav id="nav-inner" class="nav-inner">
        
            <a class="nav-item" href="/homepage/">
                <span class="nav-text">首页</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/front-end">
                <span class="nav-text">前端</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/back-end">
                <span class="nav-text">后端</span>
            </a>
        
            <a class="nav-item" href="/homepage/categories/linux">
                <span class="nav-text">linux部署</span>
            </a>
        
            <a class="nav-item" href="/homepage/tags">
                <span class="nav-text">标签</span>
            </a>
        
            <a class="nav-item" href="/homepage/archives">
                <span class="nav-text">归档</span>
            </a>
        
            <a class="nav-item" href="/homepage/about">
                <span class="nav-text">关于</span>
            </a>
        
    </nav>
</div>

    <aside id="aside" class="aside">
    <div id="aside-mask" class="aside-mask"></div>
    <div id="aside-inner" class="aside-inner">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit"><i class="icon-search-stroke"></i></button><input type="hidden" name="sitesearch" value="http://zhenglide.gitee.io/homepage"></form>

        
        
        
        

        
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#新建vue项目"><span class="toc-number">1.</span> <span class="toc-text">新建vue项目</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#安装vue脚手架3-x-版本"><span class="toc-number">1.1.</span> <span class="toc-text">安装vue脚手架3.x 版本</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#创建项目"><span class="toc-number">1.1.1.</span> <span class="toc-text">创建项目</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jest-之-helloworld"><span class="toc-number">2.</span> <span class="toc-text">jest 之 helloworld</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#方式1："><span class="toc-number">2.1.</span> <span class="toc-text">方式1：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#安装jest"><span class="toc-number">2.1.1.</span> <span class="toc-text">安装jest</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#在-Jest-中处理单文件组件"><span class="toc-number">2.1.2.</span> <span class="toc-text">在 Jest 中处理单文件组件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#为-Jest-配置-Babel"><span class="toc-number">2.1.3.</span> <span class="toc-text">为 Jest 配置 Babel</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#创建配置文件"><span class="toc-number">2.1.4.</span> <span class="toc-text">创建配置文件</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#在jest-config-js配置文件中添加以下配置"><span class="toc-number">2.1.5.</span> <span class="toc-text">在jest.config.js配置文件中添加以下配置</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#方式二"><span class="toc-number">2.2.</span> <span class="toc-text">方式二</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#自定义测试"><span class="toc-number">3.</span> <span class="toc-text">自定义测试</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#编写一个简单的组件"><span class="toc-number">3.1.</span> <span class="toc-text">编写一个简单的组件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#编写测试例子"><span class="toc-number">3.2.</span> <span class="toc-text">编写测试例子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#生成测试覆盖率报告"><span class="toc-number">3.3.</span> <span class="toc-text">生成测试覆盖率报告</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#官方文档地址"><span class="toc-number">4.</span> <span class="toc-text">官方文档地址</span></a></li></ol>
        
    </div>
</aside>

</header>

        <div id="content" class="content">
            <div id="wrapper" class="wrapper" style="max-width: 800px">
                <article class="article" itemscope itemprop="blogPost">
    
    <header class="article-header">
        
        <h1 itemprop="name">
            jest-vue测试套件使用
        </h1>
        
        <div class="article-meta clearfix">
            <a class="article-date" href="http://zhenglide.gitee.io/homepage/2020/05/06/jest-vue%E6%B5%8B%E8%AF%95%E5%A5%97%E4%BB%B6%E4%BD%BF%E7%94%A8/index.html">
    
    <i class="icon-calendar"></i>
    
    <time datetime="2020-05-06T02:33:46.000Z" itemprop="datePublished">2020-05-06</time>
</a>

            
<div class="article-tag-list">
    <i class="icon-tag"></i>
    <a class="article-tag-link" href="/homepage/tags/vue/" rel="tag">vue</a>
</div>


        </div>
    </header>
    
    <section class="article-body markdown-body">
        
        <p>本文主要讲基于vue脚手架3.x 如何搭建单元测试框架，以及简单的测试</p>
<a id="more"></a>

<h2 id="新建vue项目"><a href="#新建vue项目" class="headerlink" title="新建vue项目"></a>新建vue项目</h2><h3 id="安装vue脚手架3-x-版本"><a href="#安装vue脚手架3-x-版本" class="headerlink" title="安装vue脚手架3.x 版本"></a>安装vue脚手架3.x 版本</h3><p>使用<code>npm list -g --depth 0</code> 查看脚手架装的是vue-cli 还是@vue/cli  如果是vue-cli 使用<code>npm uninstall vue-cli -g</code> 卸载,然后使用<code>npm install -g @vue/cli</code> 重新安装新版本脚手架</p>
<h4 id="创建项目"><a href="#创建项目" class="headerlink" title="创建项目"></a>创建项目</h4><p><code>vue create vue-jest</code> 创建项目</p>
<p>选择自定义配置Manually select features  </p>
<p>选择以下配置</p>
<img src="/homepage/2020/05/06/jest-vue%E6%B5%8B%E8%AF%95%E5%A5%97%E4%BB%B6%E4%BD%BF%E7%94%A8/%E5%88%9B%E5%BB%BA%E9%A1%B9%E7%9B%AE.png" class="">

<p>选择jest</p>
<img src="/homepage/2020/05/06/jest-vue%E6%B5%8B%E8%AF%95%E5%A5%97%E4%BB%B6%E4%BD%BF%E7%94%A8/%E9%80%89%E6%8B%A9jest.png" class="">

<p>之后选择后面选项，等待创建项目</p>
<h2 id="jest-之-helloworld"><a href="#jest-之-helloworld" class="headerlink" title="jest 之 helloworld"></a>jest 之 helloworld</h2><h3 id="方式1："><a href="#方式1：" class="headerlink" title="方式1："></a>方式1：</h3><h4 id="安装jest"><a href="#安装jest" class="headerlink" title="安装jest"></a>安装jest</h4><pre><code class="bash"> npm install --save-dev jest @vue/test-utils</code></pre>
<h4 id="在-Jest-中处理单文件组件"><a href="#在-Jest-中处理单文件组件" class="headerlink" title="在 Jest 中处理单文件组件"></a>在 Jest 中处理单文件组件</h4><pre><code class="bash">npm install --save-dev vue-jest</code></pre>
<h4 id="为-Jest-配置-Babel"><a href="#为-Jest-配置-Babel" class="headerlink" title="为 Jest 配置 Babel"></a>为 Jest 配置 Babel</h4><pre><code class="bash">npm install --save-dev babel-jest</code></pre>
<h4 id="创建配置文件"><a href="#创建配置文件" class="headerlink" title="创建配置文件"></a>创建配置文件</h4><p>使用<code>npx jest --init</code> 创建配置文件</p>
{%asset_img 创建jest配置文件.png %}



<h4 id="在jest-config-js配置文件中添加以下配置"><a href="#在jest-config-js配置文件中添加以下配置" class="headerlink" title="在jest.config.js配置文件中添加以下配置"></a>在jest.config.js配置文件中添加以下配置</h4><pre><code class="js">module.exports = {
  moduleFileExtensions: [&#39;js&#39;, &#39;jsx&#39;, &#39;json&#39;, &#39;vue&#39;],
  transform: {
    &#39;^.+\\.vue$&#39;: &#39;vue-jest&#39;,
    &#39;.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$&#39;:
      &#39;jest-transform-stub&#39;,
    &#39;^.+\\.jsx?$&#39;: &#39;babel-jest&#39;
  },
  moduleNameMapper: {
    &#39;^@/(.*)$&#39;: &#39;&lt;rootDir&gt;/src/$1&#39;
  },
  snapshotSerializers: [&#39;jest-serializer-vue&#39;],
  testMatch: [
    &#39;**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)&#39;
  ],
  collectCoverageFrom: [&#39;src/utils/**/*.{js,vue}&#39;, &#39;!src/utils/auth.js&#39;, &#39;!src/utils/request.js&#39;, &#39;src/components/**/*.{js,vue}&#39;],
  coverageDirectory: &#39;&lt;rootDir&gt;/tests/unit/coverage&#39;,
  // &#39;collectCoverage&#39;: true,
  &#39;coverageReporters&#39;: [
    &#39;lcov&#39;,
    &#39;text-summary&#39;
  ],
  testURL: &#39;http://localhost/&#39;
}</code></pre>
<p>运行jest 测试项目默认的helloWord  <code>npm run test</code></p>
<h3 id="方式二"><a href="#方式二" class="headerlink" title="方式二"></a>方式二</h3><p>或者直接使用脚手架的提供的 ，就不用添加配置 ，<code>npm run test:unit</code></p>
<p>这个时候就会看到测试成功</p>
<h2 id="自定义测试"><a href="#自定义测试" class="headerlink" title="自定义测试"></a>自定义测试</h2><p>现在我们来看一个简单的例子</p>
<h3 id="编写一个简单的组件"><a href="#编写一个简单的组件" class="headerlink" title="编写一个简单的组件"></a>编写一个简单的组件</h3><pre><code class="vue">&lt;template&gt;
    &lt;div&gt;
        &lt;span v-for=&quot;item in topicList&quot; :key=&quot;item.id&quot;&gt;
             {{item.name}}
        &lt;/span&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
    name:&quot;Topic&quot;,
    data() {
        return  {
           topicList:[{
                name:&quot;主题1&quot;,
                id:1
           },{
                name:&quot;主题2&quot;,
                id:2
           }]
        };
    }
};
&lt;/script&gt;</code></pre>
<h3 id="编写测试例子"><a href="#编写测试例子" class="headerlink" title="编写测试例子"></a>编写测试例子</h3><p>在tests/unit 目录下新建 topic.spec.js 注意要以spec.js 结尾</p>
<pre><code class="javascript">import { shallowMount,mount } from &#39;@vue/test-utils&#39;
import Topic from &#39;@/components/Topic.vue&#39;
//创建测试套件
describe(&#39;测试topic&#39;, () =&gt; {
    // 挂载组件
    const wrapper = shallowMount(Topic)
    //获取组件实例
    const vm = wrapper.vm;
    // 单个测试用例
  it(&#39;测试数据是否渲染成功&#39;, () =&gt; {

    expect(vm.topicList.length).toBe(wrapper.findAll(&quot;span&quot;).length)
  })
})
</code></pre>
<p>使用npm run test 测试成功</p>
<h3 id="生成测试覆盖率报告"><a href="#生成测试覆盖率报告" class="headerlink" title="生成测试覆盖率报告"></a>生成测试覆盖率报告</h3><p>在package.json 中script 添加   “coverage”:”jest –coverage”</p>
<p>使用npm run coverage 可以生成测试报告</p>
<img src="/homepage/2020/05/06/jest-vue%E6%B5%8B%E8%AF%95%E5%A5%97%E4%BB%B6%E4%BD%BF%E7%94%A8/%E6%B5%8B%E8%AF%95%E8%A6%86%E7%9B%96%E7%8E%87.png" class="">

<h2 id="官方文档地址"><a href="#官方文档地址" class="headerlink" title="官方文档地址"></a>官方文档地址</h2><p> Jest   <a href="https://jestjs.io/docs/zh-Hans/getting-started" target="_blank" rel="noopener">https://jestjs.io/docs/zh-Hans/getting-started</a></p>
<p>vue-test <a href="https://vue-test-utils.vuejs.org/zh/guides/#起步" target="_blank" rel="noopener">https://vue-test-utils.vuejs.org/zh/guides/#%E8%B5%B7%E6%AD%A5</a></p>

        
    </section>
</article>



<a id="pagenext" href="/homepage/2020/04/20/mybaties-plus3-x%E6%95%B4%E5%90%88springboot%E6%90%AD%E5%BB%BA%E9%A1%B9%E7%9B%AE%E5%9F%BA%E7%A1%80%E6%A1%86%E6%9E%B6/" class="article-next" title="mybaties-plus3.x整合springboot搭建项目基础框架"><i class="icon-arrow-right"></i></a>


<a id="pageprev" href="/homepage/2020/05/13/mybatis%E5%85%B3%E8%81%94%E6%9F%A5%E8%AF%A2%E6%8A%A5TooManyResultException/" class="article-prev" title="mybatis关联查询报TooManyResultException"><i class="icon-arrow-left"></i></a>




            </div>
        </div>
        <footer class="footer">
    Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>, Theme by <a href="https://github.com/sanonz/hexo-theme-concise" target="_blank">Concise</a>

    
    <script>
        var _hmt = _hmt || [];
        (function () {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?b13bb4c2ef8300062aab9732bd22eae0";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>
    
</footer>

    </main>

    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.9.0/jquery.min.js"></script>
    <script type="text/javascript">
    $(function() {
        var nodes = {
            nav: $('#nav'),
            aside: $('#aside'),
            asideInner: $('#aside-inner'),
            navInner: $('#nav-inner')
        };

        var doing = false;
        nodes.asideInner.on('webkitAnimationEnd mozAnimationEnd oAnimationEnd oanimationend animationend', function() {
            if (nodes.aside.hasClass('mobile-open')) {
                nodes.aside.removeClass('mobile-open');
            } else {
                nodes.aside.removeClass('mobile-close panel-show');
            }
            doing = false;
        });
        $('#open-panel, #aside-mask').on('click', function() {
            if (doing) {
                return;
            }

            if (nodes.aside.hasClass('panel-show')) {
                nodes.aside.addClass('mobile-close');
            } else {
                nodes.aside.addClass('mobile-open panel-show');
            }
        });
        $('#open-menus').on('click', function() {
            nodes.navInner.slideToggle();
        });

        if (window.innerWidth <= 960) {
            setTimeout(function() {
                nodes.navInner.slideUp();
            }, 3000);
        }
    });
    </script>
    
        
<script src="/homepage/js/scrollspy.min.js"></script>

        <script type="text/javascript">
        $(document.body).scrollspy({target: '#aside-inner'});

        $(window).on('resize', function() {
            var hw = $('#header').width();
            var ww = $('#wrapper').width();
            var space = ($(this).width() - hw - ww) / 2 / 2;

            var pageprev = $('#pageprev');
            var pagenext = $('#pagenext');
            var avg = (pageprev.width() + pagenext.width()) / 2

            if(space > avg) {
                var len = space - avg / 2;
                var styles = {position: 'fixed', top: '50%', marginTop: - (pageprev.width() + pagenext.width()) / 4}
                pageprev.css($.extend({left: hw + len}, styles));
                pagenext.css($.extend({right: len}, styles));
            } else {
                pageprev.removeAttr('style');
                pagenext.removeAttr('style');
            }
        }).trigger('resize');
        </script>
    

</body>
</html>
